package com.example.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/*
*   能解决在触发sentinel规则后，出现'block by sentinel(Flow limiting)'的异常；直接抛出500的异常解决不了
*   只捕获sentinel异常
* */
@Component
public class ShopBlockExceptionHandler implements BlockExceptionHandler {

    /*
    *   当发生异常就会进入这个方法
    * */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Map<String, Object> map = new HashMap<>();
        if (e instanceof FlowException){
            // 限流异常
            map.put("code",-1);
            map.put("msg","限流异常");
        } else if (e instanceof DegradeException) {
            // 降级异常
            map.put("code",-2);
            map.put("msg","降级异常");
        } else if (e instanceof ParamFlowException) {
            // 热点异常
            map.put("code",-3);
            map.put("msg","热点异常");
        } else if (e instanceof AuthorityException) {
            // 授权异常
            map.put("code",-4);
            map.put("msg","限授权异常");
        } else if (e instanceof SystemBlockException) {
            // 系统异常
            map.put("code",-5);
            map.put("msg","系统异常");
        }
        String jsonString = JSON.toJSONString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
}
